import socket
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding

def encrypt(data, key, iv):
    padder = padding.PKCS7(128).padder()
    padded_data = padder.update(data) + padder.finalize()
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
    encryptor = cipher.encryptor()
    return encryptor.update(padded_data) + encryptor.finalize()

# 配置参数
key = b'this_is_a_32_byte_key_for_aes256!!'  # 32字节密钥
file_path = 'input.txt'                       # 要发送的文件
server_address = ('127.0.0.1', 9999)

# 读取文件内容
with open(file_path, 'rb') as f:
    plaintext = f.read()

# 生成加密参数
iv = os.urandom(16)
ciphertext = encrypt(plaintext, key, iv)

# 建立连接并发送数据
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(server_address)

# 发送IV和加密数据（先发送IV再发送密文）
client_socket.send(iv)
client_socket.send(len(ciphertext).to_bytes(4, 'big'))  # 发送数据长度
client_socket.sendall(ciphertext)                       # 发送全部加密数据

# 接收服务器确认
print("服务器响应:", client_socket.recv(1024).decode())
client_socket.close()